﻿using System.Data;
using System.Data.Common;

namespace StarsAdmin.Core.Extensions
{
    public static class DbContextExtension
    {
        /// <summary>
        /// 获取运行时的Sql
        /// </summary>
        /// <param name="dbCommand"></param>
        /// <returns></returns>
        public static string GetCommandText(this DbCommand dbCommand)
        {
            var sql = dbCommand.CommandText;
            foreach (DbParameter parameter in dbCommand.Parameters)
            {
                try
                {
                    string value = string.Empty;
                    switch (parameter.DbType)
                    {
                        case DbType.Date:
                            value = parameter.Value.ParseToString().ParseToDateTime().ToString("yyyy-MM-dd HH:mm:ss");
                            break;

                        default:
                            value = parameter.Value.ParseToString();
                            break;
                    }
                    sql = sql.Replace(parameter.ParameterName, value);
                } catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return sql;
        }
    }
}